// 主应用逻辑
class NamingApp {
    constructor() {
        this.favorites = this.loadFavorites();
        this.lastGeneratedNames = []; // 记录上次生成的名字
        this.allGeneratedNames = []; // 记录所有生成过的名字
        this.currentNameData = []; // 存储当前生成的完整名字数据，包括AI生成的
        this.aiEnabled = true; // AI模式开关
        this.isGenerating = false; // 防止重复调用标志
        this.aiCancelled = false; // AI调用取消标志
        this.init();
    }

    init() {
        this.setupEventListeners();
        this.displayWelcomeMessage();
        this.updateFavoritesCount();
    }

    setupEventListeners() {
        // 监听姓氏输入框的输入事件，实时更新预览
        const surnameInput = document.getElementById('surname');
        surnameInput.addEventListener('input', () => {
            this.updateNamePreviews();
        });

        // 监听筛选条件变化
        const filters = ['gender', 'nameLength', 'poetry'];
        filters.forEach(filterId => {
            document.getElementById(filterId).addEventListener('change', () => {
                this.clearResults();
            });
        });
    }

    displayWelcomeMessage() {
        const resultsContainer = document.getElementById('results-container');
        resultsContainer.innerHTML = `
            <div style="text-align: center; padding: 60px 20px; color: #666;">
                <div style="font-size: 3rem; margin-bottom: 20px;">📚</div>
                <h3 style="margin-bottom: 10px; color: #8b4513;">欢迎使用中文取名神器</h3>
                <p>每个名字都有深厚的文化底蕴和美好寓意</p>
                <p style="margin-top: 10px; font-size: 0.9rem;">请设置筛选条件，点击"生成好名字"开始</p>
                <div style="margin-top: 20px; padding: 15px; background: linear-gradient(135deg, #f8fff8, #e8f5e8); border-radius: 8px; border-left: 4px solid #4CAF50;">
                    <p style="margin: 0; font-size: 0.85rem; color: #2E7D32;">
                        🤖 已集成<strong>DeepSeek AI</strong>智能生成 - 性价比最高的AI取名体验
                    </p>
                    <p style="margin: 5px 0 0 0; font-size: 0.75rem; color: #666;">
                        每次都为您推荐全新的文雅名字，点击"AI配置"设置密钥获得最佳体验
                    </p>
                </div>
            </div>
        `;
    }

    clearResults() {
        const resultsContainer = document.getElementById('results-container');
        resultsContainer.innerHTML = '';
        this.currentNameData = []; // 清除当前名字数据
        this.displayWelcomeMessage();
    }

    clearPreviousResults() {
        const resultsContainer = document.getElementById('results-container');
        resultsContainer.innerHTML = '';
    }

    updateNamePreviews() {
        const surname = document.getElementById('surname').value.trim();
        const nameCards = document.querySelectorAll('.name-card');
        
        nameCards.forEach(card => {
            const nameTitle = card.querySelector('.name-title');
            const originalName = nameTitle.dataset.originalName;
            nameTitle.textContent = surname + originalName;
        });
    }

    // 收藏功能相关方法
    loadFavorites() {
        const stored = localStorage.getItem('namingFavorites');
        return stored ? JSON.parse(stored) : [];
    }

    saveFavorites() {
        localStorage.setItem('namingFavorites', JSON.stringify(this.favorites));
    }

    toggleFavorite(nameData) {
        const surname = document.getElementById('surname').value.trim();
        const fullName = surname + nameData.name;
        const favoriteItem = {
            ...nameData,
            fullName: fullName,
            surname: surname,
            favoriteTime: new Date().toISOString()
        };

        const existingIndex = this.favorites.findIndex(fav => 
            fav.fullName === fullName
        );

        if (existingIndex >= 0) {
            // 取消收藏
            this.favorites.splice(existingIndex, 1);
            this.showMessage('已取消收藏', 'info');
        } else {
            // 添加收藏
            this.favorites.unshift(favoriteItem);
            this.showMessage('已添加到收藏', 'success');
        }
        
        this.saveFavorites();
        this.updateFavoriteButtons();
        return existingIndex < 0; // 返回是否是新收藏
    }

    isFavorite(nameData) {
        const surname = document.getElementById('surname').value.trim();
        const fullName = surname + nameData.name;
        return this.favorites.some(fav => fav.fullName === fullName);
    }

    showMessage(message, type = 'info') {
        // 创建消息提示
        const messageEl = document.createElement('div');
        messageEl.className = `message-toast ${type}`;
        messageEl.textContent = message;
        
        let backgroundColor = '#2196F3';
        if (type === 'success') backgroundColor = '#4CAF50';
        else if (type === 'warning') backgroundColor = '#FF9800';
        else if (type === 'error') backgroundColor = '#f44336';
        
        messageEl.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: ${backgroundColor};
            color: white;
            padding: 12px 20px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.2);
            z-index: 9999;
            font-size: 14px;
            transform: translateX(100%);
            transition: transform 0.3s ease;
            max-width: 300px;
            word-wrap: break-word;
        `;
        
        document.body.appendChild(messageEl);
        
        // 动画显示
        setTimeout(() => {
            messageEl.style.transform = 'translateX(0)';
        }, 100);
        
        // 3秒后自动移除
        setTimeout(() => {
            messageEl.style.transform = 'translateX(100%)';
            setTimeout(() => {
                if (messageEl.parentNode) {
                    messageEl.parentNode.removeChild(messageEl);
                }
            }, 300);
        }, 3000);
    }

    updateFavoriteButtons() {
        const favoriteButtons = document.querySelectorAll('.favorite-btn');
        favoriteButtons.forEach(btn => {
            const nameData = JSON.parse(btn.dataset.nameData);
            const isFav = this.isFavorite(nameData);
            btn.innerHTML = isFav ? '❤️' : '🤍';
            btn.title = isFav ? '取消收藏' : '添加收藏';
        });
        this.updateFavoritesCount();
    }

    updateFavoritesCount() {
        const countEl = document.getElementById('favorites-count');
        if (countEl) {
            countEl.textContent = this.favorites.length;
        }
    }

    showFavorites() {
        const loadingEl = document.getElementById('loading');
        const resultsContainer = document.getElementById('results-container');
        
        loadingEl.classList.add('hidden');
        
        if (this.favorites.length === 0) {
            resultsContainer.innerHTML = `
                <div style="text-align: center; padding: 60px 20px; color: #666;">
                    <div style="font-size: 3rem; margin-bottom: 20px;">💝</div>
                    <h3 style="margin-bottom: 10px; color: #8b4513;">暂无收藏的名字</h3>
                    <p>快去生成一些好名字并收藏吧！</p>
                </div>
            `;
            return;
        }

        const cardsHTML = this.favorites.map(name => `
            <div class="name-card favorite-card">
                <div class="card-header">
                    <div onclick="showFavoriteDetail('${name.name}')" style="flex: 1; cursor: pointer;">
                        <div class="name-title">${name.fullName}</div>
                        <div class="name-pinyin">${name.pinyin}</div>
                    </div>
                    <button class="favorite-btn" 
                            onclick="removeFavorite('${name.fullName}')"
                            title="取消收藏">
                        ❤️
                    </button>
                </div>
                <div class="name-source" onclick="showFavoriteDetail('${name.name}')" style="cursor: pointer;">${name.source}</div>
                <div class="name-preview" onclick="showFavoriteDetail('${name.name}')" style="cursor: pointer;">${name.meaning.substring(0, 50)}...</div>
                <div class="favorite-time">收藏于 ${new Date(name.favoriteTime).toLocaleDateString()}</div>
            </div>
        `).join('');

        resultsContainer.innerHTML = `
            <div style="margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center;">
                <h3 style="color: #8b4513; margin: 0;">我的收藏 (${this.favorites.length})</h3>
                <button onclick="app.clearPreviousResults(); app.displayWelcomeMessage();" 
                        style="background: none; border: 1px solid #ddd; padding: 6px 12px; border-radius: 4px; cursor: pointer;">
                    返回生成
                </button>
            </div>
            <div class="results-container">
                ${cardsHTML}
            </div>
        `;
    }

    // ============= AI生成相关方法 =============

    async generateNames() {
        const surname = document.getElementById('surname').value.trim();
        
        if (!surname) {
            alert('请先输入姓氏再生成名字');
            document.getElementById('surname').focus();
            return;
        }

        // 防止重复调用
        if (this.isGenerating) {
            this.showMessage('正在生成中，请稍候...', 'info');
            return;
        }
        
        this.isGenerating = true;

        // 每次重新生成都清空结果
        this.clearPreviousResults();

        try {
            if (this.aiEnabled) {
                // 检查API配置
                const hasValidConfig = this.checkAIConfig();
                if (hasValidConfig) {
                    await this.generateNamesWithAI(surname);
                } else {
                    this.showAIFailure('请先配置AI API密钥才能使用AI生成功能');
                    this.showMessage('请点击"AI配置"按钮设置API密钥', 'info');
                    this.isGenerating = false;
                }
            } else {
                this.showLoadingWithStatus('智能推荐系统启动中...');
                setTimeout(() => {
                    this.generateNamesFromDatabase(surname);
                }, 300);
            }
        } catch (error) {
            console.error('生成名字时出错:', error);
            this.showAIFailure(`系统异常: ${error.message}`);
            this.isGenerating = false;
        }
    }

    // 检查AI配置是否有效
    checkAIConfig() {
        const deepseekKey = localStorage.getItem('deepseek-api-key');
        const qwenKey = localStorage.getItem('qwen-api-key');
        const zhipuKey = localStorage.getItem('zhipu-api-key');
        
        return (deepseekKey && deepseekKey !== 'your-deepseek-api-key') ||
               (qwenKey && qwenKey !== 'your-qwen-api-key') ||
               (zhipuKey && zhipuKey !== 'your-zhipu-api-key');
    }

    // 取消AI生成
    cancelAIGeneration() {
        this.aiCancelled = true;
        this.isGenerating = false;
        this.showMessage('已取消AI生成', 'warning');
        this.displayWelcomeMessage();
    }

    // AI生成名字方法 - 真正的等待，不降级
    async generateNamesWithAI(surname) {
        console.log('开始使用AI生成名字，姓氏:', surname);
        
        const gender = document.getElementById('gender').value;
        const nameLength = document.getElementById('nameLength').value;
        const poetry = document.getElementById('poetry').value;

        // 构建AI提示词
        const prompt = this.buildAIPrompt(surname, gender, nameLength, poetry);
        console.log('AI提示词:', prompt);
        
        // 记录开始时间
        const startTime = Date.now();
        let waitingTimer;
        let elapsedTime = 0;
        
        // 重置取消标志
        this.aiCancelled = false;
        
        // 启动计时器显示等待时间
        this.showLoadingWithTimer('正在调用AI生成名字', 0);
        waitingTimer = setInterval(() => {
            if (this.aiCancelled) {
                clearInterval(waitingTimer);
                return;
            }
            elapsedTime = Math.floor((Date.now() - startTime) / 1000);
            this.showLoadingWithTimer('正在调用AI生成名字', elapsedTime);
        }, 1000);
        
        try {
            console.log('开始AI调用，时间戳:', startTime);
            
            // 调用AI服务，不设置超时，让用户真正等待
            const aiGeneratedNames = await this.callAIService(prompt);
            
            // 检查是否被取消
            if (this.aiCancelled) {
                clearInterval(waitingTimer);
                console.log('AI调用已被用户取消');
                return;
            }
            
            // 计算响应时间
            const endTime = Date.now();
            const responseTime = Math.floor((endTime - startTime) / 1000);
            
            // 清除计时器
            clearInterval(waitingTimer);
            
            console.log(`AI响应时间: ${responseTime}秒`);
            console.log('AI返回的名字数据:', aiGeneratedNames);
            
            if (aiGeneratedNames && aiGeneratedNames.length > 0) {
                // 过滤重复名字
                const uniqueNames = this.filterUniqueNames(aiGeneratedNames);
                console.log('过滤后的唯一名字:', uniqueNames);
                
                if (uniqueNames.length > 0) {
                    this.lastGeneratedNames = uniqueNames.map(name => name.name);
                    this.allGeneratedNames.push(...this.lastGeneratedNames);
                    this.currentNameData = uniqueNames; // 存储完整的AI生成名字数据
                    console.log('AI生成成功，显示名字:', uniqueNames);
                    this.showMessage(`AI生成成功！用时${responseTime}秒`, 'success');
                    this.displayResults(uniqueNames);
                    this.isGenerating = false;
                    return;
                } else {
                    // 如果名字重复，重新调用AI
                    console.log('所有AI生成的名字都重复了，重新生成...');
                    this.showMessage(`AI响应用时${responseTime}秒，但名字重复，重新生成中...`, 'warning');
                    // 递归调用重新生成
                    await this.generateNamesWithAI(surname);
                    return;
                }
            } else {
                console.log('AI没有返回有效的名字数据');
                this.showMessage(`AI响应用时${responseTime}秒，但返回数据无效，请重试`, 'error');
                this.showAIFailure('AI返回数据无效，请检查API配置或重试');
                this.isGenerating = false;
            }
        } catch (error) {
            // 清除计时器
            clearInterval(waitingTimer);
            
            const errorTime = Math.floor((Date.now() - startTime) / 1000);
            console.error(`AI调用失败，用时${errorTime}秒:`, error);
            
            this.showMessage(`AI调用失败，用时${errorTime}秒: ${error.message}`, 'error');
            this.showAIFailure(`AI服务调用失败: ${error.message}`);
            this.isGenerating = false;
        }
    }

    // 传统数据库生成方法
    generateNamesFromDatabase(surname) {
        // 显示智能推荐状态
        this.showLoadingWithStatus('智能推荐系统运行中...');
        
        // 使用较短的延迟，优化用户体验
        setTimeout(() => {
            const filteredNames = this.getFilteredNames();
            
            if (filteredNames.length === 0) {
                this.showNoResults();
                return;
            }

            // 过滤重复名字
            let uniqueNames = this.filterUniqueNames(filteredNames);
            
            if (uniqueNames.length === 0) {
                // 如果没有新名字，重置历史记录
                this.lastGeneratedNames = [];
                this.allGeneratedNames = [];
                uniqueNames = this.filterUniqueNames(filteredNames);
            }

            const selectedNames = uniqueNames.slice(0, 6);

            // 为每个名字添加完整姓名
            const namesWithSurname = selectedNames.map(name => ({
                ...name,
                fullName: surname + name.name
            }));

            this.lastGeneratedNames = selectedNames.map(name => name.name);
            this.allGeneratedNames.push(...this.lastGeneratedNames);
            this.currentNameData = namesWithSurname; // 存储完整的数据库生成名字数据
            this.displayResults(namesWithSurname);
            this.isGenerating = false;
        }, 600); // 减少延迟，提升响应速度
    }

    // 构建AI提示词
    buildAIPrompt(surname, gender, nameLength, poetry) {
        let genderText = gender === 'male' ? '男孩' : gender === 'female' ? '女孩' : '不限性别';
        let lengthText = nameLength === '1' ? '单字名（1个字）' : nameLength === '2' ? '双字名（2个字）' : '单字名或双字名';
        let poetryText = this.getPoetryTypeText(poetry);
        
        let excludeText = '';
        if (this.allGeneratedNames.length > 0) {
            excludeText = `\n6. 避免使用这些已生成的名字：${this.allGeneratedNames.join('、')}`;
        }
        
        return `请为姓氏"${surname}"的${genderText}生成6个${lengthText}，要求来自${poetryText}。${excludeText}

严格按照JSON格式返回，示例格式：
[
  {
    "name": "清漪",
    "pinyin": "qīng yī", 
    "gender": "female",
    "length": 2,
    "type": "song",
    "source": "苏轼《饮湖上初晴后雨》",
    "original": "水光潋滟晴方好，山色空蒙雨亦奇",
    "meaning": "清：清澈纯净；漪：水波纹。寓意心如止水，纯净美好。",
    "fullName": "${surname}清漪"
  }
]

现在请生成6个符合要求的名字，只返回JSON数组，不要任何其他文字：`;
    }

    // 获取诗词类型文本
    getPoetryTypeText(poetry) {
        const typeMap = {
            'tang': '唐诗',
            'song': '宋词', 
            'classic': '经典古文',
            'book': '诗经楚辞',
            'all': '唐诗、宋词、诗经楚辞或经典古文'
        };
        return typeMap[poetry] || '古诗词';
    }

    // 过滤重复名字
    filterUniqueNames(names) {
        return names.filter(name => {
            return !this.lastGeneratedNames.includes(name.name);
        });
    }

    // 调用AI服务
    async callAIService(prompt) {
        // 优先尝试DeepSeek API（性价比最高）
        const deepseekKey = localStorage.getItem('deepseek-api-key');
        const qwenKey = localStorage.getItem('qwen-api-key');
        const zhipuKey = localStorage.getItem('zhipu-api-key');
        
        try {
            if (deepseekKey && deepseekKey !== 'your-deepseek-api-key') {
                console.log('尝试调用DeepSeek API...');
                return await this.callDeepSeekAPI(prompt);
            }
        } catch (error) {
            console.log('DeepSeek API调用失败，尝试其他服务', error.message);
        }
        
        try {
            if (qwenKey && qwenKey !== 'your-qwen-api-key') {
                console.log('尝试调用通义千问API...');
                return await this.callQwenAPI(prompt);
            }
        } catch (error) {
            console.log('通义千问API调用失败，尝试智谱AI', error.message);
        }
        
        try {
            if (zhipuKey && zhipuKey !== 'your-zhipu-api-key') {
                console.log('尝试调用智谱AI...');
                return await this.callZhipuAPI(prompt);
            }
        } catch (error) {
            console.log('智谱AI调用失败', error.message);
        }
        
        // 如果没有可用的API密钥或所有调用都失败
        console.log('所有AI服务均不可用');
        throw new Error('AI服务暂时不可用');
    }

    // DeepSeek API调用
    async callDeepSeekAPI(prompt) {
        const apiKey = localStorage.getItem('deepseek-api-key') || 'your-deepseek-api-key';
        
        if (!apiKey || apiKey === 'your-deepseek-api-key') {
            throw new Error('请配置DeepSeek API密钥');
        }
        
        const response = await fetch('https://api.deepseek.com/chat/completions', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                model: 'deepseek-chat',
                messages: [
                    {
                        role: 'system',
                        content: '你是中文取名专家，专门从古诗词中选取名字。必须严格按照JSON数组格式返回结果，不要任何额外文字。'
                    },
                    {
                        role: 'user',
                        content: prompt
                    }
                ],
                temperature: 0.8,
                max_tokens: 2000,
                stream: false
            })
        });

        if (!response.ok) {
            const errorData = await response.json().catch(() => ({}));
            throw new Error(`DeepSeek API调用失败: ${response.status} ${errorData.error?.message || response.statusText}`);
        }

        const data = await response.json();
        const content = data.choices?.[0]?.message?.content || '';
        
        console.log('DeepSeek API原始响应:', content);
        
        // 使用工具函数解析JSON
        const parsedData = utils.testJSONParsing(content);
        
        if (parsedData && Array.isArray(parsedData) && parsedData.length > 0) {
            // 验证每个名字对象的必需字段
            const validNames = parsedData.filter(name => 
                name.name && name.pinyin && name.source && name.meaning
            );
            
            if (validNames.length > 0) {
                const processedData = validNames.map(name => ({
                    ...name,
                    source: name.source + ' (DeepSeek AI)',
                    meaning: name.meaning + ' 【DeepSeek AI推荐】此名字经过DeepSeek智能分析，文雅大气，寓意深远。'
                }));
                
                console.log('DeepSeek API处理后的数据:', processedData);
                return processedData;
            } else {
                console.error('没有找到有效的名字数据');
            }
        }
        
        console.log('DeepSeek API响应格式错误，降级到其他服务');
        throw new Error('DeepSeek AI响应格式错误');
    }

    // 通义千问API调用
    async callQwenAPI(prompt) {
        // 注意：实际使用时需要配置API密钥
        const apiKey = localStorage.getItem('qwen-api-key') || 'your-qwen-api-key';
        
        if (apiKey === 'your-qwen-api-key') {
            throw new Error('请配置API密钥');
        }
        
        const response = await fetch('https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                model: 'qwen-turbo',
                input: {
                    messages: [
                        {
                            role: 'user',
                            content: prompt
                        }
                    ]
                },
                parameters: {
                    temperature: 0.8,
                    max_tokens: 2000
                }
            })
        });

        if (!response.ok) {
            throw new Error('API调用失败');
        }

        const data = await response.json();
        const content = data.output?.text || '';
        
        try {
            // 尝试解析JSON响应
            const jsonMatch = content.match(/\[[\s\S]*\]/);
            if (jsonMatch) {
                return JSON.parse(jsonMatch[0]);
            }
        } catch (e) {
            console.error('解析AI响应失败:', e);
        }
        
        throw new Error('AI响应格式错误');
    }

    // 智谱AI调用
    async callZhipuAPI(prompt) {
        // 注意：实际使用时需要配置API密钥
        const apiKey = localStorage.getItem('zhipu-api-key') || 'your-zhipu-api-key';
        
        if (apiKey === 'your-zhipu-api-key') {
            throw new Error('请配置API密钥');
        }
        
        const response = await fetch('https://open.bigmodel.cn/api/paas/v4/chat/completions', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                model: 'glm-4',
                messages: [
                    {
                        role: 'user',
                        content: prompt
                    }
                ],
                temperature: 0.8,
                max_tokens: 2000
            })
        });

        if (!response.ok) {
            throw new Error('API调用失败');
        }

        const data = await response.json();
        const content = data.choices?.[0]?.message?.content || '';
        
        try {
            // 尝试解析JSON响应
            const jsonMatch = content.match(/\[[\s\S]*\]/);
            if (jsonMatch) {
                return JSON.parse(jsonMatch[0]);
            }
        } catch (e) {
            console.error('解析AI响应失败:', e);
        }
        
        throw new Error('AI响应格式错误');
    }

    // 模拟AI响应（用于演示和降级）
    async simulateAIResponse(prompt) {
        // 模拟AI处理时间
        await new Promise(resolve => setTimeout(resolve, 2000));
        
        // 从数据库中选择高质量名字，模拟AI生成
        const filteredNames = this.getFilteredNames();
        const uniqueNames = this.filterUniqueNames(filteredNames);
        
        if (uniqueNames.length === 0) {
            return [];
        }
        
        // 选择评分最高的6个名字
        const topNames = uniqueNames.slice(0, 6);
        const surname = document.getElementById('surname').value.trim();
        
        return topNames.map(name => ({
            ...name,
            fullName: surname + name.name,
            source: name.source + ' (AI增强)',
            meaning: name.meaning + ' 【AI推荐】经过智能分析，此名字文雅大气，非常适合您的需求。'
        }));
    }

    // ============= 数据库相关方法 =============

    getFilteredNames() {
        const gender = document.getElementById('gender').value;
        const nameLength = document.getElementById('nameLength').value;
        const poetry = document.getElementById('poetry').value;

        let filteredNames = nameDatabase.filter(name => {
            if (gender !== 'all' && name.gender !== gender) return false;
            if (nameLength !== 'all' && name.length.toString() !== nameLength) return false;
            if (poetry !== 'all' && name.type !== poetry) return false;
            return true;
        });

        // 智能排序：优先选择更文雅大气的名字
        return this.intelligentSortNames(filteredNames);
    }

    intelligentSortNames(names) {
        // 文雅大气的关键词
        const elegantKeywords = ['君', '清', '雅', '轩', '承', '致', '景', '翰', '凌', '俊', '澜', '星'];
        const literaryTypes = ['book', 'classic']; // 优先诗经楚辞和经典古文
        
        return names.sort((a, b) => {
            let scoreA = 0;
            let scoreB = 0;
            
            // 名字包含文雅字符加分
            elegantKeywords.forEach(keyword => {
                if (a.name.includes(keyword)) scoreA += 3;
                if (b.name.includes(keyword)) scoreB += 3;
            });
            
            // 文学类型加分
            if (literaryTypes.includes(a.type)) scoreA += 2;
            if (literaryTypes.includes(b.type)) scoreB += 2;
            
            // 寓意长度加分（更详细的寓意通常更好）
            if (a.meaning.length > 50) scoreA += 1;
            if (b.meaning.length > 50) scoreB += 1;
            
            // 按分数降序排列
            return scoreB - scoreA;
        });
    }

    shuffleArray(array) {
        const shuffled = [...array];
        for (let i = shuffled.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
        }
        return shuffled;
    }

    // ============= UI相关方法 =============

    showLoading() {
        const loadingEl = document.getElementById('loading');
        const resultsContainer = document.getElementById('results-container');
        
        loadingEl.classList.remove('hidden');
        resultsContainer.innerHTML = '';
    }

    showLoadingWithStatus(statusText) {
        const resultsContainer = document.getElementById('results-container');
        resultsContainer.innerHTML = `
            <div style="text-align: center; padding: 60px 20px; color: #666;">
                <div class="loading-spinner" style="margin: 0 auto 20px; width: 40px; height: 40px; border: 3px solid #f3f3f3; border-top: 3px solid #4CAF50; border-radius: 50%; animation: spin 1s linear infinite;"></div>
                <h3 style="margin-bottom: 10px; color: #4CAF50;">${statusText}</h3>
                <p style="font-size: 0.9rem; color: #999;">请稍候，正在为您生成好名字...</p>
            </div>
        `;
        
        // 确保CSS动画样式存在
        if (!document.querySelector('#loading-styles')) {
            const style = document.createElement('style');
            style.id = 'loading-styles';
            style.textContent = `
                @keyframes spin {
                    0% { transform: rotate(0deg); }
                    100% { transform: rotate(360deg); }
                }
            `;
            document.head.appendChild(style);
        }
    }

    showLoadingWithTimer(statusText, elapsedSeconds) {
        const resultsContainer = document.getElementById('results-container');
        
        // 根据等待时间调整提示信息
        let waitingMessage = 'AI正在精心为您选择最美好的名字';
        let encouragement = '请耐心等待，好名字值得等待 ✨';
        
        if (elapsedSeconds > 15) {
            waitingMessage = 'AI正在深度思考，为您生成独特的名字';
            encouragement = '稍等片刻，AI正在创作专属于您的好名字 🎨';
        } else if (elapsedSeconds > 30) {
            waitingMessage = 'AI正在查阅古籍，寻找最有文化底蕴的名字';
            encouragement = '越是用心的作品，越需要时间雕琢 📚';
        }
        
        resultsContainer.innerHTML = `
            <div style="text-align: center; padding: 60px 20px; color: #666;">
                <div class="loading-spinner" style="margin: 0 auto 20px; width: 40px; height: 40px; border: 3px solid #f3f3f3; border-top: 3px solid #2196F3; border-radius: 50%; animation: spin 1s linear infinite;"></div>
                <h3 style="margin-bottom: 10px; color: #2196F3;">${statusText}...</h3>
                <div style="font-size: 1.2rem; color: #2196F3; margin: 15px 0; font-weight: bold;">
                    ⏱️ ${elapsedSeconds}秒
                </div>
                <p style="font-size: 0.9rem; color: #999;">${waitingMessage}</p>
                <p style="font-size: 0.8rem; color: #bbb; margin-top: 10px;">${encouragement}</p>
                ${elapsedSeconds > 10 ? `
                    <button onclick="app.cancelAIGeneration()" style="
                        background: #ff6b6b; 
                        color: white; 
                        border: none; 
                        padding: 8px 16px; 
                        border-radius: 4px; 
                        cursor: pointer; 
                        margin-top: 15px;
                        font-size: 0.85rem;
                    ">
                        ❌ 取消等待
                    </button>
                ` : ''}
            </div>
        `;
        
        // 确保CSS动画样式存在
        if (!document.querySelector('#loading-styles')) {
            const style = document.createElement('style');
            style.id = 'loading-styles';
            style.textContent = `
                @keyframes spin {
                    0% { transform: rotate(0deg); }
                    100% { transform: rotate(360deg); }
                }
            `;
            document.head.appendChild(style);
        }
    }

    showAIFailure(errorMessage) {
        const resultsContainer = document.getElementById('results-container');
        resultsContainer.innerHTML = `
            <div style="text-align: center; padding: 60px 20px; color: #666;">
                <div style="font-size: 3rem; margin-bottom: 20px;">🤖💔</div>
                <h3 style="margin-bottom: 15px; color: #f44336;">AI服务暂时不可用</h3>
                <p style="color: #999; margin-bottom: 20px;">${errorMessage}</p>
                <div style="background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 15px; margin: 20px auto; max-width: 400px;">
                    <p style="margin: 0; color: #856404; font-size: 0.9rem;">
                        💡 <strong>建议：</strong><br>
                        1. 检查API密钥配置<br>
                        2. 确保网络连接正常<br>
                        3. 稍后重试生成
                    </p>
                </div>
                <button onclick="app.generateNames()" style="background: #4CAF50; color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer; margin-top: 15px;">
                    🔄 重新生成
                </button>
            </div>
        `;
    }

    showNoResults() {
        const loadingEl = document.getElementById('loading');
        const resultsContainer = document.getElementById('results-container');
        
        loadingEl.classList.add('hidden');
        resultsContainer.innerHTML = `
            <div style="text-align: center; padding: 60px 20px; color: #666;">
                <div style="font-size: 3rem; margin-bottom: 20px;">😔</div>
                <h3 style="margin-bottom: 10px; color: #8b4513;">暂无符合条件的名字</h3>
                <p>请尝试调整筛选条件，获取更多选择</p>
            </div>
        `;
        this.isGenerating = false;
    }

    displayResults(names) {
        const loadingEl = document.getElementById('loading');
        const resultsContainer = document.getElementById('results-container');
        
        loadingEl.classList.add('hidden');
        
        const cardsHTML = names.map(name => {
            const isFav = this.isFavorite(name);
            return `
            <div class="name-card">
                <div class="card-header">
                    <div onclick="showNameDetail('${name.name}')" style="flex: 1; cursor: pointer;">
                        <div class="name-title" data-original-name="${name.name}">${name.fullName}</div>
                        <div class="name-pinyin">${name.pinyin}</div>
                    </div>
                    <button class="favorite-btn" 
                            data-name-data='${JSON.stringify(name)}' 
                            onclick="toggleFavorite(this)"
                            title="${isFav ? '取消收藏' : '添加收藏'}">
                        ${isFav ? '❤️' : '🤍'}
                    </button>
                </div>
                <div class="name-source" onclick="showNameDetail('${name.name}')" style="cursor: pointer;">${name.source}</div>
                <div class="name-preview" onclick="showNameDetail('${name.name}')" style="cursor: pointer;">${name.meaning.substring(0, 50)}...</div>
            </div>
        `;
        }).join('');

        resultsContainer.innerHTML = cardsHTML;

        // 添加渐入动画
        setTimeout(() => {
            const cards = document.querySelectorAll('.name-card');
            cards.forEach((card, index) => {
                setTimeout(() => {
                    card.style.opacity = '0';
                    card.style.transform = 'translateY(20px)';
                    card.style.transition = 'all 0.3s ease';
                    
                    setTimeout(() => {
                        card.style.opacity = '1';
                        card.style.transform = 'translateY(0)';
                    }, 50);
                }, index * 100);
            });
        }, 100);
    }

    showNameDetail(nameName) {
        const surname = document.getElementById('surname').value.trim();
        
        // 首先在当前生成的数据中查找（包括AI生成的名字）
        let nameData = this.currentNameData.find(name => name.name === nameName);
        
        // 如果没找到，再在数据库中查找
        if (!nameData) {
            nameData = nameDatabase.find(name => name.name === nameName);
            if (nameData) {
                nameData = {...nameData, fullName: surname + nameData.name};
            }
        }
        
        if (!nameData) {
            console.log('未找到名字数据:', nameName);
            return;
        }

        this.showNameDetailFromData(nameData);
    }

    showNameDetailFromData(nameData) {
        const modal = document.getElementById('name-modal');
        const modalName = document.getElementById('modal-name');
        const modalPinyin = document.getElementById('modal-pinyin');
        const modalSource = document.getElementById('modal-source');
        const modalOriginal = document.getElementById('modal-original');
        const modalMeaning = document.getElementById('modal-meaning');

        modalName.textContent = nameData.fullName;
        modalPinyin.textContent = nameData.pinyin;
        modalSource.textContent = nameData.source;
        modalOriginal.textContent = nameData.original;
        modalMeaning.textContent = nameData.meaning;

        modal.classList.remove('hidden');
        document.body.style.overflow = 'hidden';
    }

    closeModal() {
        const modal = document.getElementById('name-modal');
        modal.classList.add('hidden');
        document.body.style.overflow = 'auto';
    }
}

// 全局函数
function generateNames() {
    app.generateNames();
}

function showNameDetail(nameName) {
    app.showNameDetail(nameName);
}

function closeModal() {
    app.closeModal();
}

function toggleFavorite(button) {
    const nameData = JSON.parse(button.dataset.nameData);
    const isNowFavorite = app.toggleFavorite(nameData);
    button.innerHTML = isNowFavorite ? '❤️' : '🤍';
    button.title = isNowFavorite ? '取消收藏' : '添加收藏';
}

function showFavorites() {
    app.showFavorites();
}

function removeFavorite(fullName) {
    app.favorites = app.favorites.filter(fav => fav.fullName !== fullName);
    app.saveFavorites();
    app.showFavorites();
    app.showMessage('已取消收藏', 'info');
}

function showFavoriteDetail(nameName) {
    const favoriteData = app.favorites.find(fav => fav.name === nameName);
    if (favoriteData) {
        app.showNameDetailFromData(favoriteData);
    }
}

// AI配置相关函数
function showConfigModal() {
    const modal = document.getElementById('config-modal');
    
    // 加载已保存的配置
    const deepseekKey = localStorage.getItem('deepseek-api-key') || '';
    const qwenKey = localStorage.getItem('qwen-api-key') || '';
    const zhipuKey = localStorage.getItem('zhipu-api-key') || '';
    
    document.getElementById('deepseek-api-key').value = deepseekKey === 'your-deepseek-api-key' ? '' : deepseekKey;
    document.getElementById('qwen-api-key').value = qwenKey === 'your-qwen-api-key' ? '' : qwenKey;
    document.getElementById('zhipu-api-key').value = zhipuKey === 'your-zhipu-api-key' ? '' : zhipuKey;
    
    modal.classList.remove('hidden');
    document.body.style.overflow = 'hidden';
}

function closeConfigModal() {
    const modal = document.getElementById('config-modal');
    modal.classList.add('hidden');
    document.body.style.overflow = 'auto';
}

function saveConfig() {
    const deepseekKey = document.getElementById('deepseek-api-key').value.trim();
    const qwenKey = document.getElementById('qwen-api-key').value.trim();
    const zhipuKey = document.getElementById('zhipu-api-key').value.trim();
    
    let hasConfig = false;
    
    if (deepseekKey) {
        localStorage.setItem('deepseek-api-key', deepseekKey);
        hasConfig = true;
    }
    if (qwenKey) {
        localStorage.setItem('qwen-api-key', qwenKey);
        hasConfig = true;
    }
    if (zhipuKey) {
        localStorage.setItem('zhipu-api-key', zhipuKey);
        hasConfig = true;
    }
    
    if (hasConfig) {
        app.showMessage('配置已保存，重新生成名字时将使用AI服务', 'success');
    } else {
        app.showMessage('请至少配置一个API密钥', 'info');
    }
    
    closeConfigModal();
}

function clearConfig() {
    localStorage.removeItem('deepseek-api-key');
    localStorage.removeItem('qwen-api-key');
    localStorage.removeItem('zhipu-api-key');
    document.getElementById('deepseek-api-key').value = '';
    document.getElementById('qwen-api-key').value = '';
    document.getElementById('zhipu-api-key').value = '';
    
    app.showMessage('配置已清除，将使用内置智能推荐', 'info');
}

// 测试DeepSeek API连接
async function testDeepSeekAPI() {
    const apiKey = document.getElementById('deepseek-api-key').value.trim();
    
    if (!apiKey) {
        app.showMessage('请先输入DeepSeek API密钥', 'info');
        return;
    }
    
    // 显示测试中状态
    const testButton = event.target;
    const originalText = testButton.textContent;
    testButton.textContent = '测试中...';
    testButton.disabled = true;
    
    try {
        const response = await fetch('https://api.deepseek.com/chat/completions', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                model: 'deepseek-chat',
                messages: [
                    {
                        role: 'user',
                        content: '请回复"连接成功"四个字'
                    }
                ],
                max_tokens: 10,
                stream: false
            })
        });

        if (response.ok) {
            const data = await response.json();
            const content = data.choices?.[0]?.message?.content || '';
            if (content.includes('连接成功') || content.includes('成功')) {
                app.showMessage('DeepSeek API连接成功！', 'success');
            } else {
                app.showMessage('DeepSeek API连接成功，可以正常使用', 'success');
            }
        } else {
            const errorData = await response.json().catch(() => ({}));
            app.showMessage(`连接失败: ${errorData.error?.message || response.statusText}`, 'info');
        }
    } catch (error) {
        app.showMessage(`连接失败: ${error.message}`, 'info');
    } finally {
        testButton.textContent = originalText;
        testButton.disabled = false;
    }
}

// 点击模态框外部关闭
document.addEventListener('click', (e) => {
    const nameModal = document.getElementById('name-modal');
    const configModal = document.getElementById('config-modal');
    
    if (e.target === nameModal) {
        closeModal();
    }
    if (e.target === configModal) {
        closeConfigModal();
    }
});

// 键盘 ESC 关闭模态框
document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
        closeModal();
        closeConfigModal();
    }
});

// 初始化应用
let app;
document.addEventListener('DOMContentLoaded', () => {
    app = new NamingApp();
    console.log('中文取名神器 (AI增强版) 初始化完成');
});

// 调试函数 - 可以在浏览器控制台中调用
window.debugDeepSeek = async function(surname = '李') {
    console.log('开始调试DeepSeek API...');
    
    const prompt = `请为姓氏"${surname}"的男孩生成3个双字名，要求来自唐诗。

严格按照JSON格式返回，示例格式：
[
  {
    "name": "清漪",
    "pinyin": "qīng yī", 
    "gender": "male",
    "length": 2,
    "type": "tang",
    "source": "李白《将进酒》",
    "original": "君不见黄河之水天上来",
    "meaning": "清：清澈纯净；漪：水波纹。寓意心如止水，纯净美好。",
    "fullName": "${surname}清漪"
  }
]

现在请生成3个符合要求的名字，只返回JSON数组，不要任何其他文字：`;

    try {
        const result = await app.callDeepSeekAPI(prompt);
        console.log('调试成功，返回结果:', result);
        return result;
    } catch (error) {
        console.error('调试失败:', error);
        return null;
    }
};

// 添加一些实用的工具函数
const utils = {
    // 检查名字的五行属性（简化版本）
    checkElementBalance(name) {
        // 这里可以扩展五行检测逻辑
        return "五行平衡";
    },
    
    // 计算笔画数（简化版本）
    calculateStrokes(name) {
        // 这里可以扩展笔画计算逻辑
        return Math.floor(Math.random() * 20) + 10;
    },
    
    // 生成随机推荐
    getRandomRecommendation() {
        const recommendations = [
            "建议选择寓意吉祥的名字",
            "可以考虑与生辰八字相配的名字",
            "诗词出处的名字更有文化内涵",
            "单字名简洁大方，双字名寓意丰富",
            "AI智能推荐更文雅大气的名字"
        ];
        return recommendations[Math.floor(Math.random() * recommendations.length)];
    },

    // API密钥配置助手
    configureAPIKey(service, apiKey) {
        localStorage.setItem(`${service}-api-key`, apiKey);
        console.log(`${service} API密钥已配置`);
    },

    // 测试JSON解析
    testJSONParsing(content) {
        console.log('测试JSON解析，原始内容:', content);
        
        // 尝试多种JSON提取方式
        let jsonMatch = content.match(/\[[\s\S]*?\]/);
        
        // 如果没找到，尝试更宽松的匹配
        if (!jsonMatch) {
            jsonMatch = content.match(/```json\s*([\s\S]*?)\s*```/);
            if (jsonMatch) {
                jsonMatch[0] = jsonMatch[1];
            }
        }
        
        // 如果还没找到，尝试直接解析整个内容
        if (!jsonMatch) {
            // 移除可能的markdown标记
            const cleanContent = content.replace(/```json|```/g, '').trim();
            if (cleanContent.startsWith('[') && cleanContent.endsWith(']')) {
                jsonMatch = [cleanContent];
            }
        }
        
        if (jsonMatch) {
            try {
                const parsed = JSON.parse(jsonMatch[0]);
                console.log('解析成功:', parsed);
                return parsed;
            } catch (e) {
                console.error('JSON解析失败:', e);
            }
        } else {
            console.log('未找到JSON数据');
        }
        
        return null;
    }
};